#include "logindialog.h"
#include "ui_logindialog.h"

#include "SysHelper.hpp"

LoginDialog::LoginDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::LoginDialog)
{
    ui->setupUi(this);

    connect(ui->login_pushButton, &QPushButton::clicked, this, &LoginDialog::on_loginPushButton_clicked);

    // 输入焦点 强制初始置于密码框
    ui->usr_lineEdit->setFocus();
}

LoginDialog::~LoginDialog()
{
    delete ui;
}

void LoginDialog::on_loginPushButton_clicked() {
    qDebug() << "the login button has been pressed!";
    showWeiChatWindow();
}

void LoginDialog::showWeiChatWindow() {

    qDebug() << "the show WeChat Window has been called!";

    QString userfile_path;
    if (getSysType() == 1) {
        userfile_path = "C:\\userlog.xml";
    }
    else if (getSysType() == 0) {
        userfile_path = "/home/userlog.xml";
    }
    else {
        userfile_path = "userlog.xml";
    }
    QFile file(userfile_path);
    if (!file.open(QIODevice::ReadOnly)) {
        // 文件打开失败，抛出异常
        //throw std::runtime_error("Failed to open file.");
        qDebug() << "fail to open file!" ;
    }

    mydoc_.setContent(&file);

    QDomElement root = mydoc_.documentElement();

    if (root.hasChildNodes()) {
        QDomNodeList userList = root.childNodes();
        bool exist = false;
        for (int i = 0; i < userList.count(); ++i) {
            QDomNode user = userList.at(i);
            QDomNodeList record = user.childNodes();

            QString usr_name = record.at(0).toElement().text();
            QString usr_pwd = record.at(1).toElement().text();

            qDebug() << "the usr name is:" << usr_name;
            qDebug() << "the usr pwd is:" << usr_pwd;
            qDebug() << "the usr_name is:" << ui->usr_lineEdit->text();

            if (usr_name == ui->usr_lineEdit->text()) {
                exist = true;

                if (!(usr_pwd == ui->pwd_lineEdit->text()) ) {
                    qDebug() << "pwd is not correct!";
                    QMessageBox::warning(0, QObject::tr("提示"), "口令错误，请重新输入！");
                    ui->pwd_lineEdit->clear();
                    ui->pwd_lineEdit->setFocus();
                    return;
                }
            }
            else
                qDebug() << "用户名不匹配";
        }

        if (!exist) {
            qDebug() << "usr not existed!";

            QMessageBox::warning(0, QObject::tr("提示"), "此用户不存在！");
            ui->usr_lineEdit->clear();
            ui->pwd_lineEdit->clear();
            ui->usr_lineEdit->setFocus();
            return;
        }

        // 用户存在且密码通过
        weichat_window_ = new MainWindow(0);
        weichat_window_->setWindowTitle(ui->usr_lineEdit->text());
        weichat_window_->show();

    }

    // qDebug() << "usr not existed!";

    // QMessageBox::warning(0, QObject::tr("提示"), "此用户不存在！");
}
